﻿using System;
using System.Runtime.InteropServices;

namespace Btstack
{
    public partial class Bluetooth
    {
        public delegate void AttReadCallbackType(ushort ConHandle, ushort AttributeHandle, ushort offset, IntPtr buffer, ushort BufferSize);
        public delegate int AttWriteCallbackType(ushort ConHandle, ushort AttributeHandle, ushort TransactionMode, ushort offset, IntPtr buffer, ushort BufferSize);

        [DllImport("btstack-c.dll", EntryPoint = "att_server_register_packet_handler")]
        private static extern void AttServerRegisterPacketHandler(BtstackPacketHandlerType handler);

        [DllImport("btstack-c.dll", EntryPoint = "att_server_init")]
        private static extern void AttServerInit(IntPtr db, AttReadCallbackType ReadCallback, AttWriteCallbackType WriteCallback);

        [DllImport("btstack-c.dll", EntryPoint = "att_server_request_can_send_now_event")]
        public static extern void AttServerRequestCanSendNowEvent(ushort ConHandle);

        private static ushort AttEventConnectedGetHandle(byte[] packet)
        {
            return BitConverter.ToUInt16(packet, 9);
        }

        private static ushort AttEventMtuExchangeCompleteGetMTU(byte[] packet)
        {
            return BitConverter.ToUInt16(packet, 4);
        }

        private static ushort AttEventMtuExchangeCompleteGetHandle(byte[] packet)
        {
            return BitConverter.ToUInt16(packet, 2);
        }

        private static ushort AttEventDisconnectedGetHandle(byte[] packet)
        {
            return BitConverter.ToUInt16(packet, 2);
        }

        private static void AttServerInit(byte[] db, AttReadCallbackType ReadCallback, AttWriteCallbackType WriteCallback)
        {
            var DbPtr = Marshal.AllocHGlobal(db.Length);
            Marshal.Copy(db, 0, DbPtr, db.Length);

            AttServerInit(DbPtr, ReadCallback, WriteCallback);
        }
    }
}
